import type { AxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios';
import axios from 'axios';
import qs from 'qs';
import { ElMessage } from 'element-plus';
import { AxiosCanceler } from './axiosCancel';
import { AxiosLoad } from './axiosLoad';
import { RequestOptions } from "../../../types/index";



import type { Ref } from "vue"

class VAxios {
  private axiosInstance
  constructor(options: AxiosRequestConfig) {
    this.axiosInstance = axios.create(options);
    this.setupInterceptors();
  }
  getAxios(): AxiosInstance {
    return this.axiosInstance;
  }

  setupInterceptors() {
    const axiosCanceler = new AxiosCanceler();
    this.axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
      axiosCanceler.addPending(config);
      return config;
    }, undefined);

    this.axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
      res && axiosCanceler.removePending(res.config);
      if (res.data) {
        if (res.data.code == 1000 || res.data.code == 500 || res.data.code == 401 || res.data.code == 403 || res.data.code == 400) {
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          })
        }
        if (res.data.code == 401) {
          window.location.href = '/login'
          // $router.replace({ path: '/login' })
        }
        // res.data.code == 401
      }
      return res.data;
    }, undefined);
  }
  uploadFile<T>(options: RequestOptions<T>) {
    const { url, data, loading } = options
    const axiosLoad = new AxiosLoad(loading as Ref<boolean>);
    axiosLoad.load(url)
    return this.axiosInstance.request({
      url,
      method: 'POST',
      data,
      headers: {
        'Content-type': 'multipart/form-data;charset=UTF-8',
        ignoreCancelToken: true,
      },
    }).then((res: any) => {
      if (res.code == 1000) {
        options.fail && options.fail(res);
      }
      if (res.code == 200) {
        options.success && options.success(res.data);
      }
      axiosLoad.removeLoad()
    }).catch((err: any) => {
      options.fail && options.fail(err);
      axiosLoad.removeLoad()
    });;
  }
  get<T>(options: RequestOptions<T>) {
    return this.request<T>({ ...options, method: "GET" })
  }

  post<T>(options: RequestOptions<T>) {
    return this.request<T>({ ...options, method: "POST" })
  }
  request<T>(options: RequestOptions<T>) {
    let { url, method, data, params, loading } = options
    const axiosLoad = new AxiosLoad(loading as Ref<boolean>);
    axiosLoad.load(url)
    return new Promise((resolve, reject) => {
      this.axiosInstance.request({
        url,
        method,
        params: params || '',
        data: qs.stringify(data || {})
      }).then((res: any) => {
        if (res.code == 1000) {
          options.fail && options.fail(res);
        }
        if (res.code == 200) {
          options.success && options.success(res.data || res);
        } else {
          options.fail && options.fail(res);
        }

        axiosLoad.removeLoad()
        resolve(res);
      }).catch((err: any) => {
        options.fail && options.fail(err);
        axiosLoad.removeLoad()
        reject(err);
      });
    })

  }

}



export const ajax = new VAxios({
  timeout: 1000 * 600,
  // 如果服务端 设置了  origin = *  ,withCredentials 要改为 false
  withCredentials: true,
  baseURL: '',
  headers: {
    // application/json;charset=UTF-8
    'Content-Type': 'application/x-www-form-urlencoded'
    // 'Content-Type': 'application/json; charset=utf-8'
  }
})
// 